package com.gitee.magic.context.editor;

import java.util.ArrayList;
import java.util.List;

import com.gitee.magic.context.PropertyConverterEditor;
import com.gitee.magic.context.RestConverterEditor;
import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.json.JsonArray;

/**
 * @author start
 */
@SuppressWarnings("deprecation")
public class JsonArrayConverterEditor extends AbstractConverterEditor<JsonArray> {

	private AbstractConverterEditor<?> editor;
	
	public JsonArrayConverterEditor(Class<?> prototype) {
		super(prototype);
		editor=PropertyConverterEditor.getBasicConverter(prototype);
	}

	@Override
	public void restore(Object value) {
		if (value != null) {
			JsonArray arrays=(JsonArray)value;
			setSource(arrays);
			if(editor==null) {
				setValue(RestConverterEditor.converterList(getPrototype(), arrays));
			}else {
				List<Object> content=new ArrayList<>();
				for(int i=0;i<arrays.length();i++) {
					Object val=arrays.get(i);
					editor.restore(val);
					content.add(editor.getValue());
				}
				setValue(content);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public JsonArray converter() {
		if (getValue() == null) {
			return null;
		}
		List<Object> content = (List<Object>) getValue();
		JsonArray jsons = new JsonArray();
		if(editor==null) {
			for (Object value : content) {
				jsons.put(RestConverterEditor.converterJsonObject(value));
			}
		}else {
			for (Object value : content) {
				editor.setValue(value);
				jsons.put(editor.getSource());
			}
		}
		return jsons;
	}

	@Override
	public Object getSource() {
		return converter();
	}

}
